﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;

namespace OpenRPOSBackOffice
{
    public partial class MenuItems : Page
    {
        public ObservableCollection<RecipeData> recipeDataSource = new ObservableCollection<RecipeData>();
        public ObservableCollection<ServiceReferenceOpenRPOS.MenuCategory> menuItemMenuCategoryRecords = new ObservableCollection<ServiceReferenceOpenRPOS.MenuCategory>();
        public string strSelectedRecipe = "", strSelectedMenuItem="";
        int currentMenuCategorySelectedIndex = 0;
        List<int> menuOptionIDs = new List<int>();

        public MenuItems()
        {
            InitializeComponent();
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            init();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        public async void initMenuItems(bool showWaitCursor)
        {
            if (showWaitCursor)
            {
                Globals.showWaitCursor(true);
                await Globals.db.GetMenuItemObjects("Active=1 order by FullName");
            }
            // Populate menu items
            cmbMenuItems.Items.Clear();
            if (Globals.db.MenuItemRecords.Count() > 0)
            {
                foreach (ServiceReferenceOpenRPOS.MenuItem mi in Globals.db.MenuItemRecords)
                {
                    cmbMenuItems.Items.Add(mi.col_FullName);
                }
                cmbMenuItems.SelectedIndex = 0;
                tbShortName.Text = Globals.db.MenuItemRecords[0].col_ShortName;
                tbPrice.Text = Globals.db.MenuItemRecords[0].col_Price.ToString("N");
                tbDescription.Text = Globals.db.MenuItemRecords[0].col_Description;
                cbEnabled.IsChecked = Globals.db.MenuItemRecords[0].col_Enabled;
                cmbMenuCategory.SelectedIndex = -1;
                if (cmbMenuCategory.Items.Count() > 0)
                {
                    foreach (ServiceReferenceOpenRPOS.MenuCategory mc in menuItemMenuCategoryRecords)
                    {
                        if (mc.col_ID == Globals.db.MenuItemRecords[0].col_MenuCategoryID)
                            cmbMenuCategory.SelectedValue = mc.col_Name;
                    }
                }
                // Load recipes
                cmbRecipe.Items.Clear();
                foreach (ServiceReferenceOpenRPOS.RecipeSummary rs in Globals.db.RecipeSummaryRecords)
                {
                    cmbRecipe.Items.Add(rs.col_Name);
                }
                if (cmbRecipe.Items.Count() > 0)
                {
                    if (cbRecipe.IsChecked==true)
                    {
                        try
                        {
                            var menuItemRecipe = Globals.db.RecipeSummaryRecords.Single(i => i.col_ID == Globals.db.MenuItemRecords[0].col_RecipeSummaryID);
                            cmbRecipe.SelectedValue = menuItemRecipe.col_Name;
                        }
                        catch (Exception) { cmbRecipe.SelectedIndex = 0; }
                    }
                    else cmbRecipe.SelectedIndex = 0;
                }
            }
            // Check selected menu item
            if (strSelectedMenuItem != "")
            {
                cmbMenuItems.SelectedItem = strSelectedMenuItem;
                strSelectedMenuItem = "";
            }

            if (showWaitCursor) Globals.showWaitCursor(false);
        }

        public async void initMenuCategories(bool showWaitCursor)
        {
            if (showWaitCursor)
            {
                Globals.showWaitCursor(true);
                await Globals.db.GetMenuCategoryObjects("Active=1 order by Name");
            }
            // Populate menu categories...
            cmbMenuCategory.Items.Clear();
            menuItemMenuCategoryRecords.Clear();
            cmbMenuCategory.SelectedIndex = -1;
            if (Globals.db.MenuCategoryRecords.Count() > 0)
            {
                foreach (ServiceReferenceOpenRPOS.MenuCategory mc in Globals.db.MenuCategoryRecords)
                {
                    cmbMenuCategory.Items.Add(mc.col_Name);
                    menuItemMenuCategoryRecords.Add(mc);
                }
            }
            await Globals.db.GetMenuCategoryObjects("Active=1 order by Precedence");
            lbMenuCategories.Items.Clear();
            if (Globals.db.MenuCategoryRecords.Count() > 0)
            {
                foreach (ServiceReferenceOpenRPOS.MenuCategory mc in Globals.db.MenuCategoryRecords)
                {
                    lbMenuCategories.Items.Add(mc.col_Name);
                }
                lbMenuCategories.SelectedIndex = currentMenuCategorySelectedIndex;
                currentMenuCategorySelectedIndex = 0;
            }
            lbMenuCategories.Focus();
            if (showWaitCursor) Globals.showWaitCursor(false);
        }

        public async void initUnits(bool showWaitCursor)
        {
            if (showWaitCursor)
            {
                Globals.showWaitCursor(true);
                await Globals.db.GetUnitObjects("1=1 order by Name");
            }
            // Get units
            cmbIngredientUnits.Items.Clear();
            cmbUnits.Items.Clear();
            if (Globals.db.UnitRecords.Count() > 0)
            {
                foreach (ServiceReferenceOpenRPOS.Unit unit in Globals.db.UnitRecords)
                {
                    cmbIngredientUnits.Items.Add(unit.col_Name);
                    cmbUnits.Items.Add(unit.col_Name);
                }
            }
            if (cmbUnits.Items.Count() > 0)
                cmbUnits.SelectedIndex = 0;
            if (showWaitCursor) Globals.showWaitCursor(false);
        }

        public async void initIngredients(bool showWaitCursor)
        {
            if (showWaitCursor)
            {
                Globals.showWaitCursor(true);
                await Globals.db.GetIngredientObjects("Active=1 order by Name");
            }
            // Get ingredients
            cmbIngredients.Items.Clear();
            tbCostPerUnit.Text = "";
            tbCount.Text = "";
            if (Globals.db.IngredientRecords.Count() > 0)
            {
                foreach (ServiceReferenceOpenRPOS.Ingredient ingredient in Globals.db.IngredientRecords)
                {
                    cmbIngredients.Items.Add(ingredient.col_Name);
                }
                cmbIngredients.SelectedIndex = 0;
            }
            if (showWaitCursor) Globals.showWaitCursor(false);
        }

        public async void initMenuOptions()
        {
            if (cmbOptionGroups.SelectedIndex >= 0)
            {
                // Load option group options....
                lbOptions.Items.Clear();
                menuOptionIDs.Clear();
                await Globals.db.GetMenuOptionObjects("");
                foreach (ServiceReferenceOpenRPOS.MenuItem mi in Globals.db.MenuItemRecords)
                    foreach (ServiceReferenceOpenRPOS.MenuOption mo in Globals.db.MenuOptionRecords)
                        if (mo.col_MenuItemID == mi.col_ID && mo.col_OptionGroupID == Globals.db.OptionGroupRecords[cmbOptionGroups.SelectedIndex].col_ID)
                        {
                            lbOptions.Items.Add(mi.col_FullName);
                            menuOptionIDs.Add(mo.col_ID);
                        }
            }
        }

        public async void initOptionGroups(bool showWaitCursor)
        {
            if (showWaitCursor)
            {
                Globals.showWaitCursor(true);
                await Globals.db.GetOptionGroupObjects("Active=1 order by Name");
            }
            // Get Option Groups
            cmbOptionGroups.Items.Clear();
            if (Globals.db.OptionGroupRecords.Count() > 0)
            {
                foreach (ServiceReferenceOpenRPOS.OptionGroup og in Globals.db.OptionGroupRecords)
                {
                    cmbOptionGroups.Items.Add(og.col_Name);
                }
                cmbOptionGroups.SelectedIndex = 0;
            }
            if (showWaitCursor) Globals.showWaitCursor(false);
        }

        public async void initRecipeDetail()
        {
            // Load recipe detail records for selected record
            if (cmbRecipes.SelectedIndex >= 0)
            {
                await Globals.db.GetRecipeDetailObjects("RecipeSummaryID=" + Globals.db.RecipeSummaryRecords[cmbRecipes.SelectedIndex].col_ID);
                recipeDataSource.Clear();
                // Load detail records into the list
                foreach (ServiceReferenceOpenRPOS.RecipeDetail rd in Globals.db.RecipeDetailRecords)
                {
                    RecipeData recipeData = new RecipeData();
                    recipeData.recipeDetail = rd;
                    try
                    {
                        var ingredientItem = Globals.db.IngredientRecords.Single(i => i.col_ID == rd.col_IngredientID);
                        recipeData.IngredientName = ingredientItem.col_Name;
                    }
                    catch (Exception) { }
                    try
                    {
                        var unitItem = Globals.db.UnitRecords.Single(i => i.col_ID == rd.col_UnitID);
                        recipeData.UnitName = unitItem.col_Name;
                    }
                    catch (Exception) { }
                    recipeData.Quantity = rd.col_Quantity;
                    recipeDataSource.Add(recipeData);
                }
                dgRecipeItems.ItemsSource = recipeDataSource;
            }
        }

        public async void initRecipes(bool showWaitCursor)
        {
            if (showWaitCursor)
            {
                Globals.showWaitCursor(true);
                await Globals.db.GetRecipeSummaryObjects("Active=1 order by Name");
            }
            // Get Recipes...
            cmbRecipes.Items.Clear();
            if (Globals.db.RecipeSummaryRecords.Count() > 0)
            {
                foreach (ServiceReferenceOpenRPOS.RecipeSummary rs in Globals.db.RecipeSummaryRecords)
                {
                    cmbRecipes.Items.Add(rs.col_Name);
                }
                if (strSelectedRecipe != "")
                {
                    cmbRecipes.SelectedValue = strSelectedRecipe;
                    strSelectedRecipe = "";
                }
                else
                    cmbRecipes.SelectedIndex = 0;
            }
            if (showWaitCursor) Globals.showWaitCursor(false);
        }

        // Executes when the user navigates to this page.
        public async void init()
        {
            Globals.showWaitCursor(true);
            // Load data...
            await Globals.db.GetMenuItemObjects("Active=1 order by FullName");
            await Globals.db.GetMenuCategoryObjects("Active=1 order by Name");
            await Globals.db.GetIngredientObjects("Active=1 order by Name");
            await Globals.db.GetUnitObjects("1=1 order by Name");
            await Globals.db.GetRecipeSummaryObjects("Active=1 order by Name");
            await Globals.db.GetOptionGroupObjects("Active=1 order by Name");
            // Initialze the various fields
            initMenuCategories(false);
            initMenuItems(false);
            initUnits(false);
            initIngredients(false);
            initOptionGroups(false);
            initRecipes(false);
            Globals.menuItems = this;
            Globals.showWaitCursor(false);
        }

        private async void btnUpdateIngredients_Click(object sender, RoutedEventArgs e)
        {
            if (cmbIngredients.SelectedIndex >= 0)
            {
                // Update the selected ingredient
                ServiceReferenceOpenRPOS.Ingredient ingr = Globals.db.IngredientRecords[cmbIngredients.SelectedIndex];
                try { ingr.col_CostPerUnit = Convert.ToDecimal(tbCostPerUnit.Text); }
                catch (Exception) { }
                ingr.bFilterCostPerUnit = true;
                try { ingr.col_ActualCount = Convert.ToDouble(tbCount.Text); }
                catch (Exception) { }
                ingr.bFilterActualCount = true;
                if (cmbIngredientUnits.SelectedIndex >= 0)
                {
                    ingr.col_UnitID = Globals.db.UnitRecords[cmbIngredientUnits.SelectedIndex].col_ID;
                    ingr.bFilterUnitID = true;
                }
                ingr.col_LastUpdated = DateTime.Now;
                ingr.bFilterLastUpdated = true;
                await Globals.db.UpdateIngredientObject(ingr);
                cmbIngredients_SelectionChanged(sender, null);
            }
        }

        private void btnAddMenuItem_Click(object sender, RoutedEventArgs e)
        {
            // Add a new menu item...
            AddMenuItemDialog amid = new AddMenuItemDialog();
            amid.Show();
        }

        private async void btnRemoveMenuItem_Click(object sender, RoutedEventArgs e)
        {
            if (cmbMenuItems.Items.Count() > 0)
            {
                if (MessageBox.Show("Are you sure you want to remove the selected menu item?", "Confirm", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    // Remove the selected menu item
                    Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex].col_Active = false;
                    Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex].bFilterActive = true;
                    await Globals.db.UpdateMenuItemObject(Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex]);
                    initMenuItems(true);
                }
            }
        }

        private void btnEditMenuItem_Click(object sender, RoutedEventArgs e)
        {
            if (cmbMenuItems.Items.Count() > 0)
            {
                // Edit the selected item
                EditMenuItemDialog emid = new EditMenuItemDialog();
                emid.tbMenuItemName.Text = Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex].col_FullName;
                emid.tbMenuItemName.SelectionStart = emid.tbMenuItemName.Text.Length;
                emid.Show();
            }
        }

        private async void btnUpdateMenuItem_Click(object sender, RoutedEventArgs e)
        {
            if (cmbMenuItems.Items.Count() > 0)
            {
                Globals.showWaitCursor(true);
                // Update the selected menu item
                Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex].col_ShortName = tbShortName.Text;
                Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex].bFilterShortName = true;
                try { Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex].col_Price = Convert.ToDecimal(tbPrice.Text); }
                catch (Exception) {}
                Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex].bFilterPrice = true;
                Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex].col_Description = tbDescription.Text;
                Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex].bFilterDescription = true;
                Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex].col_Enabled = cbEnabled.IsChecked == true;
                Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex].bFilterEnabled = true;
                if (cbRecipe.IsChecked == true && cmbRecipe.Items.Count() > 0)
                    Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex].col_RecipeSummaryID = Globals.db.RecipeSummaryRecords[cmbRecipe.SelectedIndex].col_ID;
                else
                    Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex].col_RecipeSummaryID = 0;
                Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex].bFilterRecipeSummaryID = true;
                Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex].col_MenuCategoryID = (cmbMenuCategory.SelectedIndex >= 0) ? 
                    menuItemMenuCategoryRecords[cmbMenuCategory.SelectedIndex].col_ID : 0;
                Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex].bFilterMenuCategoryID = true;
                await Globals.db.UpdateMenuItemObject(Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex]);
                Globals.showWaitCursor(false);
                MessageBox.Show("Menu item has been updated.");
            }
        }

        private void cmbMenuItems_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // Fill-in the selected menu item information
            if (cmbMenuItems.SelectedIndex >= 0)
            {
                tbShortName.Text = Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex].col_ShortName;
                tbPrice.Text = Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex].col_Price.ToString("N");
                tbDescription.Text = Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex].col_Description;
                cbEnabled.IsChecked = Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex].col_Enabled;
                var recSumRecs=new ObservableCollection<ServiceReferenceOpenRPOS.RecipeSummary>
                    (Globals.db.RecipeSummaryRecords.Where(x => x.col_ID == Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex].col_RecipeSummaryID && x.col_Active));
                // Determine whether or not this menu item has an associated recipe
                if ((Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex].col_RecipeSummaryID > 0) &&
                    (recSumRecs.Count() != 0))
                {
                    cbRecipe.IsChecked = true;
                    cmbRecipe.Visibility = Visibility.Visible;
                    cmbRecipe.SelectedValue = recSumRecs[0].col_Name; 
                }
                else
                {
                    cbRecipe.IsChecked = false;
                    cmbRecipe.Visibility = Visibility.Collapsed;
                    cmbRecipe.SelectedIndex = 0;
                }
                // Determine what menu category should be used...
                cmbMenuCategory.SelectedIndex = -1;
                if (Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex].col_MenuCategoryID > 0 && cmbMenuCategory.Items.Count() > 0)
                {
                    foreach (ServiceReferenceOpenRPOS.MenuCategory mc in menuItemMenuCategoryRecords)
                    {
                        if (mc.col_ID == Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex].col_MenuCategoryID)
                            cmbMenuCategory.SelectedValue = mc.col_Name;
                    }
                }                
            }
        }

        private void btnAddMenuCategory_Click(object sender, RoutedEventArgs e)
        {
            AddMenuCategoryDialog amcd = new AddMenuCategoryDialog();
            amcd.Show();
        }

        private void cbRecipe_Checked(object sender, RoutedEventArgs e)
        {
            cmbRecipe.Visibility = Visibility.Visible;
        }

        private void cbRecipe_Unchecked(object sender, RoutedEventArgs e)
        {
            cmbRecipe.Visibility = Visibility.Collapsed;
        }

        private async void btnUpdateMenuCategory_Click(object sender, RoutedEventArgs e)
        {
            if (lbMenuCategories.SelectedIndex >= 0)
            {
                Globals.db.MenuCategoryRecords[lbMenuCategories.SelectedIndex].col_Visible = (cbMenuCategoryVisible.IsChecked == true);
                Globals.db.MenuCategoryRecords[lbMenuCategories.SelectedIndex].bFilterVisible = true;
                await Globals.db.UpdateMenuCategoryObject(Globals.db.MenuCategoryRecords[lbMenuCategories.SelectedIndex]);
            }
        }

        private void btnEditMenuCategory_Click(object sender, RoutedEventArgs e)
        {
            if (lbMenuCategories.SelectedIndex >= 0)
            {
                EditMenuCategoryDialog emcd = new EditMenuCategoryDialog();
                emcd.selectedMenuCategory = Globals.db.MenuCategoryRecords[lbMenuCategories.SelectedIndex];
                emcd.tbMenuCategoryName.Text = emcd.selectedMenuCategory.col_Name;
                emcd.tbMenuCategoryName.SelectionStart = emcd.tbMenuCategoryName.Text.Length;
                emcd.Show();
            }
        }

        private async void btnRemoveMenuCategory_Click(object sender, RoutedEventArgs e)
        {
            if (lbMenuCategories.SelectedIndex >= 0)
            {
                if (MessageBox.Show("Are you sure you want to remove the selected menu category?", "Confirm", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    // Remove the selected menu category
                    await Globals.db.DeleteMenuCategoryObject(Globals.db.MenuCategoryRecords[lbMenuCategories.SelectedIndex]);
                    initMenuCategories(true);
                    initMenuItems(true);
                }
            }
        }

        private async void btnUpMenuCategory_Click(object sender, RoutedEventArgs e)
        {
            if (lbMenuCategories.SelectedIndex > 0)
            {
                // Swap positions with the category above....
                currentMenuCategorySelectedIndex = lbMenuCategories.SelectedIndex - 1;
                short precedence=Globals.db.MenuCategoryRecords[lbMenuCategories.SelectedIndex].col_Precedence;
                Globals.db.MenuCategoryRecords[lbMenuCategories.SelectedIndex].col_Precedence =
                    Globals.db.MenuCategoryRecords[lbMenuCategories.SelectedIndex-1].col_Precedence;
                Globals.db.MenuCategoryRecords[lbMenuCategories.SelectedIndex - 1].col_Precedence = precedence;
                Globals.db.MenuCategoryRecords[lbMenuCategories.SelectedIndex].bFilterPrecedence = true;
                Globals.db.MenuCategoryRecords[lbMenuCategories.SelectedIndex - 1].bFilterPrecedence = true;
                await Globals.db.UpdateMenuCategoryObject(Globals.db.MenuCategoryRecords[lbMenuCategories.SelectedIndex]);
                await Globals.db.UpdateMenuCategoryObject(Globals.db.MenuCategoryRecords[lbMenuCategories.SelectedIndex - 1]);
                initMenuCategories(true);
            }
        }

        private async void btnDownMenuCategory_Click(object sender, RoutedEventArgs e)
        {
            if (lbMenuCategories.SelectedIndex >= 0 && lbMenuCategories.SelectedIndex<lbMenuCategories.Items.Count()-1)
            {
                // Swap positions with the category above....
                currentMenuCategorySelectedIndex = lbMenuCategories.SelectedIndex + 1;
                short precedence = Globals.db.MenuCategoryRecords[lbMenuCategories.SelectedIndex].col_Precedence;
                Globals.db.MenuCategoryRecords[lbMenuCategories.SelectedIndex].col_Precedence =
                    Globals.db.MenuCategoryRecords[lbMenuCategories.SelectedIndex + 1].col_Precedence;
                Globals.db.MenuCategoryRecords[lbMenuCategories.SelectedIndex + 1].col_Precedence = precedence;
                Globals.db.MenuCategoryRecords[lbMenuCategories.SelectedIndex].bFilterPrecedence = true;
                Globals.db.MenuCategoryRecords[lbMenuCategories.SelectedIndex + 1].bFilterPrecedence = true;
                await Globals.db.UpdateMenuCategoryObject(Globals.db.MenuCategoryRecords[lbMenuCategories.SelectedIndex]);
                await Globals.db.UpdateMenuCategoryObject(Globals.db.MenuCategoryRecords[lbMenuCategories.SelectedIndex + 1]);
                initMenuCategories(true);
            }
        }

        private void lbMenuCategories_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // Set the state of the "Visible" checkbox
            if (lbMenuCategories.SelectedIndex >= 0)
                cbMenuCategoryVisible.IsChecked = Globals.db.MenuCategoryRecords[lbMenuCategories.SelectedIndex].col_Visible;
        }

        private void btnAddUnits_Click(object sender, RoutedEventArgs e)
        {
            // Add a new unit...
            AddUnitDialog aud = new AddUnitDialog();
            aud.Show();
        }

        private void btnEditUnits_Click(object sender, RoutedEventArgs e)
        {
            // Update the selected unit
            if (cmbUnits.SelectedIndex >= 0)
            {
                EditUnitDialog eud = new EditUnitDialog();
                eud.unit = Globals.db.UnitRecords[cmbUnits.SelectedIndex];
                eud.tbUnitFullName.Text = eud.unit.col_Name;
                eud.tbUnitShortName.Text = eud.unit.col_ShortName;
                eud.tbUnitShortName.SelectionStart = eud.tbUnitShortName.Text.Length;
                eud.tbUnitFullName.SelectionStart = eud.tbUnitFullName.Text.Length;
                eud.Show();
            }
        }

        private async void btnRemoveUnits_Click(object sender, RoutedEventArgs e)
        {
            if (cmbUnits.SelectedIndex >= 0)
            {
                if (MessageBox.Show("Are you sure you want to remove the selected unit?", "Confirm", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    // Remove the selected unit...
                    await Globals.db.DeleteUnitObject(Globals.db.UnitRecords[cmbUnits.SelectedIndex]);
                    initUnits(true);
                    initIngredients(true);
                }
            }
        }

        private void btnAddIngredient_Click(object sender, RoutedEventArgs e)
        {
            AddIngredientDialog aid = new AddIngredientDialog();
            aid.Show();
        }

        private void btnEditIngredients_Click(object sender, RoutedEventArgs e)
        {
            if (cmbIngredients.SelectedIndex >= 0)
            {
                EditIngredientDialog eid = new EditIngredientDialog();
                eid.ingr = Globals.db.IngredientRecords[cmbIngredients.SelectedIndex];
                eid.tbIngredientName.Text = eid.ingr.col_Name;
                eid.tbIngredientName.SelectionStart = eid.tbIngredientName.Text.Length;
                eid.Show();
            }
        }

        private async void btnRemoveIngredient_Click(object sender, RoutedEventArgs e)
        {
            if (cmbIngredients.SelectedIndex >= 0)
            {
                if (MessageBox.Show("Are you sure you want to remove the selected ingredient?", "Confirm", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    // Set the selected ingredient to inactive
                    Globals.db.IngredientRecords[cmbIngredients.SelectedIndex].col_Active = false;
                    Globals.db.IngredientRecords[cmbIngredients.SelectedIndex].bFilterActive = true;
                    await Globals.db.UpdateIngredientObject(Globals.db.IngredientRecords[cmbIngredients.SelectedIndex]);
                    initIngredients(true);
                }
            }
        }

        private void cmbIngredients_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbIngredients.SelectedIndex >= 0)
            {
                // Load the proper ingredient information
                ServiceReferenceOpenRPOS.Ingredient ingr = Globals.db.IngredientRecords[cmbIngredients.SelectedIndex];
                tbCostPerUnit.Text = ingr.col_CostPerUnit.ToString("N");
                tbCount.Text = ingr.col_ActualCount.ToString();
                foreach (ServiceReferenceOpenRPOS.Unit unit in Globals.db.UnitRecords)
                {
                    if (unit.col_ID == ingr.col_UnitID)
                        cmbIngredientUnits.SelectedValue = unit.col_Name;
                }
            }
        }

        private void btnAddOptionGroup_Click(object sender, RoutedEventArgs e)
        {
            AddOptionGroupDialog aogd = new AddOptionGroupDialog();
            aogd.Show();
        }

        private void btnEditOptionGroup_Click(object sender, RoutedEventArgs e)
        {
            if (cmbOptionGroups.SelectedIndex >= 0)
            {
                EditOptionGroupDialog eogd = new EditOptionGroupDialog();
                eogd.og = Globals.db.OptionGroupRecords[cmbOptionGroups.SelectedIndex];
                eogd.tbOptionGroupName.Text = eogd.og.col_Name;
                eogd.cbExclusive.IsChecked = eogd.og.col_Exclusive;
                eogd.tbOptionGroupName.SelectionStart = eogd.tbOptionGroupName.Text.Length;
                eogd.Show();
            }
        }

        private async void btnRemoveOptionGroup_Click(object sender, RoutedEventArgs e)
        {
            if (cmbOptionGroups.SelectedIndex >= 0)
            {
                if (MessageBox.Show("Are you sure you want to remove the selected option group?", "Confirm", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    // Remove the option group
                    Globals.db.OptionGroupRecords[cmbOptionGroups.SelectedIndex].col_Active = false;
                    Globals.db.OptionGroupRecords[cmbOptionGroups.SelectedIndex].bFilterActive = true;
                    await Globals.db.UpdateOptionGroupObject(Globals.db.OptionGroupRecords[cmbOptionGroups.SelectedIndex]);
                    initOptionGroups(true);
                }
            }
        }

        private void btnAddOptionGroupItem_Click(object sender, RoutedEventArgs e)
        {
            AddMenuOptionDialog amod = new AddMenuOptionDialog();
            amod.init();
            amod.Show();
        }

        public void cmbOptionGroups_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbOptionGroups.SelectedIndex >= 0)
                initMenuOptions();
        }

        private async void btnRemoveOptionGroupItem_Click(object sender, RoutedEventArgs e)
        {
            // Remove the selected option
            if (lbOptions.SelectedIndex >= 0)
            {
                if (MessageBox.Show("Are you sure you want to remove the selected option?", "Confirm", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    // Remove the option 
                    ServiceReferenceOpenRPOS.MenuOption mo = new ServiceReferenceOpenRPOS.MenuOption();
                    mo.col_ID = menuOptionIDs[lbOptions.SelectedIndex];
                    await Globals.db.DeleteMenuOptionObject(mo);
                    initMenuOptions();
                }
            }
        }

        private void btnAddRecipe_Click(object sender, RoutedEventArgs e)
        {
            AddRecipeDialog ard = new AddRecipeDialog();
            ard.Show();
        }

        private void btnEditRecipe_Click(object sender, RoutedEventArgs e)
        {
            if (cmbRecipes.SelectedIndex >= 0)
            {
                EditRecipeDialog erd = new EditRecipeDialog();
                erd.tbRecipeName.Text = cmbRecipes.SelectedValue.ToString();
                erd.tbRecipeName.SelectionStart = erd.tbRecipeName.Text.Length;
                erd.rs = Globals.db.RecipeSummaryRecords[cmbRecipes.SelectedIndex];
                erd.Show();
            }
        }

        private async void btnRemoveRecipe_Click(object sender, RoutedEventArgs e)
        {
            // Remove the selected recipe
            if (cmbRecipes.SelectedIndex >= 0)
            {
                if (MessageBox.Show("Are you sure you want to remove the selected recipe?", "Confirm", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    // Remove the option group
                    Globals.db.RecipeSummaryRecords[cmbRecipes.SelectedIndex].col_Active = false;
                    Globals.db.RecipeSummaryRecords[cmbRecipes.SelectedIndex].bFilterActive = true;
                    await Globals.db.UpdateRecipeSummaryObject(Globals.db.RecipeSummaryRecords[cmbRecipes.SelectedIndex]);
                    initRecipes(true);
                }
            }
        }

        private void btnAddRecipeItem_Click(object sender, RoutedEventArgs e)
        {
            if (cmbRecipes.SelectedIndex >= 0)
            {
                AddRecipeItemDialog arid = new AddRecipeItemDialog();
                arid.rs = Globals.db.RecipeSummaryRecords[cmbRecipes.SelectedIndex];
                arid.init();
                arid.Show();
            }
        }

        private void cmbRecipes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            initRecipeDetail();
        }

        private void btnEditRecipeItem_Click(object sender, RoutedEventArgs e)
        {
            if (cmbRecipes.SelectedIndex >= 0 && dgRecipeItems.SelectedIndex >= 0)
            {
                EditRecipeItemDialog erid = new EditRecipeItemDialog();
                erid.rs = Globals.db.RecipeSummaryRecords[cmbRecipes.SelectedIndex];
                RecipeData recipeData=(RecipeData)(dgRecipeItems.SelectedItem);
                erid.rd = recipeData.recipeDetail;
                erid.init();
                erid.cmbIngredient.SelectedValue = recipeData.IngredientName;
                erid.cmbUnit.SelectedValue = recipeData.UnitName;
                erid.tbQuantity.Text = recipeData.Quantity.ToString("N");
                erid.Show();
            }
        }

        private async void btnRemoveRecipeItem_Click(object sender, RoutedEventArgs e)
        {
            // Remove the selected option
            if (dgRecipeItems.SelectedIndex >= 0)
            {
                if (MessageBox.Show("Are you sure you want to remove the selected ingredient?", "Confirm", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    // Remove the option 
                    ServiceReferenceOpenRPOS.RecipeDetail rd = new ServiceReferenceOpenRPOS.RecipeDetail();
                    RecipeData recipeData = (RecipeData)(dgRecipeItems.SelectedItem);
                    await Globals.db.DeleteRecipeDetailObject(recipeData.recipeDetail);
                    initRecipeDetail();
                }
            }
        }

        private void btnOptions_Click(object sender, RoutedEventArgs e)
        {
            Options options = new Options();
            options.menuItemID = Globals.db.MenuItemRecords[cmbMenuItems.SelectedIndex].col_ID;
            options.init();
            options.Show();
        }

    }

    public class RecipeData
    {
        public string IngredientName { get; set; }
        public string UnitName { get; set; }
        public double Quantity { get; set; }
        public ServiceReferenceOpenRPOS.RecipeDetail recipeDetail { get; set; }
    }

}
